﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.Practices.Unity;
using WebShop.Contracts;
using WebShop.DAL.Interfaces;
using Webdiyer.WebControls.Mvc;

namespace WebShop.DAL.Repositories
{
    public class SupplierRepository : ISupplierRepository
    {
        [Dependency]
        public NWData Db { get; set; }

        public void Create(Supplier objectToCreate)
        {
            Db.DataContext.Suppliers.Add(objectToCreate);
        }

        public void Delete(int id)
        {
            Db.DataContext.Entry(Get(id)).State = EntityState.Deleted;
        }

        public void Edit(Supplier objectToUpdate)
        {
            Db.DataContext.Entry(objectToUpdate).State = EntityState.Modified;
        }

        public Supplier Get(int id)
        {
            return Db.DataContext.Suppliers.Find(id);
        }

        public Supplier Find(System.Linq.Expressions.Expression<Func<Supplier, bool>> predicate)
        {
            return Db.DataContext.Suppliers.SingleOrDefault(predicate);
        }

        public IEnumerable<Supplier> List()
        {
            return Db.DataContext.Suppliers.ToList();
        }

        public PagedList<Supplier> List(int? page, int pageSize)
        {
            return Db.DataContext.Suppliers.ToPagedList(page.GetValueOrDefault(1), pageSize);
        }

        public PagedList<Supplier> FindList(int? page, int pageSize, System.Linq.Expressions.Expression<Func<Supplier, bool>> predicate = null, System.Linq.Expressions.Expression<Func<Supplier, string>> orderBy = null, bool ascending = true)
        {
            var query = Db.DataContext.Suppliers.AsQueryable();

            if (predicate != null)
            {
                query = query.Where(predicate);
            }

            if (orderBy != null)
            {
                if (ascending)
                {
                    query = query.OrderBy(orderBy);
                }
                else
                {
                    query = query.OrderByDescending(orderBy);
                }
            }
            else
            {
                query = query.OrderBy(s => s.CompanyName);
            }

            return query.ToPagedList(page.GetValueOrDefault(1), pageSize);
        }


        public void SaveChanges()
        {
            Db.DataContext.SaveChanges();
        }


        public void Detach(Supplier objectToDetach)
        {
            Db.DataContext.Entry(objectToDetach).State = EntityState.Detached;
        }
    }
}